﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZSZ.CommonMVC;
using ZSZ.DTO.Enums;
using ZSZ.IService;
using ZSZ.Website.Areas.WebAdmin.Common;
using ZSZ.Website.Areas.WebAdmin.Filters;
using ZSZ.Website.Areas.WebAdmin.Models;
using static ZSZ.Common.CommonHelper;

namespace ZSZ.Website.Areas.WebAdmin.Controllers
{
    public class HomeController : Controller
    {
        public IAdminUserService userService { get; set; }
        // GET: WebAdmin/Home
        public ActionResult Index()
        {
            long? userId = AdminHelper.GetUserId(HttpContext);
            if (userId == null)
            {
                return Redirect("~/WebAdmin/Home/Login");
            }
            var user = userService.GetDTOById((long)userId);
            return View(user);
        }

        public ActionResult Logout()
        {
            Session.Abandon();//销毁Session
            return Redirect("~/WebAdmin/Home/Login");
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = MVCHelper.GetValidMsg(ModelState)
                });
            }

            //注意：验证漏洞。验证后销毁
            if (model.validateCode.ToLower() != ((string)TempData["ValidateCode"]).ToLower())
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "验证码错误" });
            }

            var user = userService.GetByName(model.userName);
            if (user==null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "用户名或者密码错误" });
            }

            AdminLoginResult result = userService.CheckLogin(model.userName, model.password);
            if (result == AdminLoginResult.Success)
            {
                //登录成功
                userService.LoginSuccess(model.userName);
                //Session中保存当前登录用户Id
                Session["LoginUserId"] = userService.GetByName(model.userName).Id;
                //给后面检查“当前Session登录的这个用户有没有***的权限”
                return Json(new AjaxResult { Status = "ok" });
            }
            else if (result == AdminLoginResult.UserDisable)
            {
                //TimeSpan代表时间段，日期相减就代表相差的时间段
                TimeSpan? leftTimeSpan =TimeSpan.FromMinutes(30) - (DateTime.Now - user.LastLoginErrorDateTime);

                return Json(new AjaxResult { Status = "error", ErrorMsg = "管理员账号账号已被锁定，请"+ (int)leftTimeSpan.Value.TotalMinutes + "分钟后再试"
                });
            }
            else if (result == AdminLoginResult.UserDisable)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "管理员账号已被禁用" });
            }
            else
            {
                //登录失败
                int tryTimes= userService.LoginError(model.userName);
                return Json(new AjaxResult { Status = "error", ErrorMsg = "用户名或者密码错误，还有" + tryTimes + "次尝试机会" });
            }
        }


        /// <summary>
        /// 验证码测试
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidateCode()
        {
            //首先实例化验证码的类  
            ValidateCode validateCode = new ValidateCode();
            //生成验证码指定的长度  
            string code = validateCode.GetRandomString(4);
            TempData["ValidateCode"] = code;
            //创建验证码的图片  
            byte[] bytes = validateCode.CreateImage(code);
            //最后将验证码返回  
            return File(bytes, @"image/jpeg");
        }
    }
}